using System;
using UnityEngine;
using Game.Controllers;

namespace Game.Controllers.Character
{
	public class CharacterMovementController
	{
		CharacterState _characterState = CharacterState.Idle;
		bool _characterDirectionRight = true;
		Transform _transform;
		Animation _animation;
		CharacterMotorMovement _movement; //para saber el movimiento del character, dirección, velocidad...
		Vector3 _lastPosition;
		Vector3 _direction;
		
		public CharacterMovementController () {}
		
		public void SetTransform (Transform transform)
		{
			_transform = transform;
		}
		
		public void SetAnimation( Animation animation )
		{
			_animation = animation;
		}
		
		public void SetCharacterMovement( CharacterMotorMovement movement ) {
			_movement = movement;
		}
		
		public void SetCharacterDirection( Vector3 direction ){
			_direction = direction;	
		}
		
		public void ChangeAnimationState( CharacterState newState ) 
		{
			_characterState = newState;
		}
		
		public void Update() {
			this.UpdateDirection();
			this.UpdateAnimations();
		}
		
		public void UpdateDirection() {
			float xdiff = _transform.position.x - _lastPosition.x;
			
			if( xdiff < 0 ) {
				this.FlipCharacter( true );
			} else if( xdiff > 0 ) {
				this.FlipCharacter( false );
			}
			_lastPosition = _transform.position;
		}
		
		public void UpdateAnimations() {
			switch( _characterState ){
				case CharacterState.Jumping:
					_animation.CrossFade("jump");
					break;
				case CharacterState.Idle:
					_animation.CrossFade("idle");
					break;
				case CharacterState.Walking:
					_animation.CrossFade("walk");
					break;
				case CharacterState.Greeting:
					_animation.CrossFade("hello");
					break;
				default:
					_animation.Stop();
					break;
			}
		}
		
		public void FlipCharacter( bool toRight ) 
		{
			if( !_characterDirectionRight && toRight ) {
				_transform.Rotate(0,-90,0);
				_characterDirectionRight = toRight;
			} else if( _characterDirectionRight && !toRight) {
				_transform.Rotate(0,90,0);
				_characterDirectionRight = toRight;
			}			
		}
		
		public bool isLookingAtRight() {
			return _characterDirectionRight;
		}
	}
}

